package cn.tjad.tjad2.module.user.adapter;

import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.tjad.tjad2.R;
import cn.tjad.tjad2.data.event.OnCheckedEvent;
import cn.tjad.tjad2.module.common.adapter.SimpleRecyclerViewAdapter;
import cn.tjad.tjad2.module.common.viewholder.EmptyViewHolder;
import cn.tjad.tjad2.module.common.viewholder.SimpleBaseViewHolder;
import cn.tjad.tjad2.module.user.viewholder.UserSelectViewHolder;

public class UserSelectAdapter extends SimpleRecyclerViewAdapter<Serializable> {

    private List<Serializable> selectedData = new ArrayList<>();

    public UserSelectAdapter(List<Serializable> data) {
        super(data);
        EventBus.getDefault().register(this);
    }

    @Override
    protected SimpleBaseViewHolder<Serializable> onCreateNormalViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.user_select_item, parent, false);
        UserSelectViewHolder viewHolder = new UserSelectViewHolder(view);
        return viewHolder;
    }

    @Override
    protected void fillEmptyViewData(EmptyViewHolder holder) {
        holder.setData("无成员", 0);
    }

    @Override
    public void onBindViewHolder(@NonNull SimpleBaseViewHolder<Serializable> holder, int position) {
        super.onBindViewHolder(holder, position);
        if (holder instanceof UserSelectViewHolder) {
            if (selectedData.contains(getItemData(position))) {
                ((UserSelectViewHolder) holder).setChecked(true);
            } else {
                ((UserSelectViewHolder) holder).setChecked(false);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OnCheckedEvent event) {
        if (event.isChecked()) {
            if (!selectedData.contains(event.getObject())) {
                selectedData.add((Serializable) event.getObject());
            }
        } else {
            if (selectedData.contains(event.getObject())) {
                selectedData.remove(event.getObject());
            }
        }
    }

    public List<Serializable> getSelectedData() {
        return selectedData;
    }

    public void toogleCheckedPosition(int positon) {
        Serializable data = getItemData(positon);
        if (selectedData.contains(data)) {
            selectedData.remove(data);
        } else {
            selectedData.add(data);
        }
        notifyDataSetChanged();
    }

    public void clearSelectedData() {
        selectedData.clear();
    }

    public void onDestroy() {
        EventBus.getDefault().unregister(this);
    }
}
